<template>
  <div class="container">
    <div class="grid">
      <a href="#" class="item" v-for="item in items" :key="item.id" @click="handleItemClick(item, $event)" @contextmenu.prevent="handleRightClick(item)">
        <div class="item-text">{{ item.title }}</div>
        <!-- 动画边框 -->
        <span class="border-line top"></span>
        <span class="border-line right"></span>
        <span class="border-line bottom"></span>
        <span class="border-line left"></span>
        <button v-if="isAdmin && itemToDelete === item" class="delete-button" @click.stop="showDeleteConfirm(item)">删除</button>
      </a>
    </div>
    <!-- 添加主页、添加按钮 -->
    <div class="back-home-button">
      <a @click="goToHome" class="action-button">
        <span class="button-content">主页</span>
        <span class="button-glow"></span>
        <span class="button-hover"></span>
      </a>
      <a v-if="isAdmin" @click="showAddModal = true" class="action-button add">
        <span class="button-content">添加</span>
        <span class="button-glow"></span>
        <span class="button-hover"></span>
      </a>
    </div>

    <!-- 添加模态框 -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <h2 class="modal-title">添加新项目</h2>
        <div class="input-group">
          <input v-model="newItem.title" class="modal-input" placeholder="标题"/>
          <input v-model="newItem.description" class="modal-input" placeholder="URL"/>
        </div>
        <div class="modal-buttons">
          <button class="modal-button cancel" @click="showAddModal = false">取消</button>
          <button class="modal-button confirm" @click="addNewItem">确定</button>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteModal" class="modal">
      <div class="modal-content delete-confirm">
        <h2 class="modal-title">确认删除</h2>
        <p class="delete-message">是否确认删除 "{{ itemToDelete?.title }}"？</p>
        <div class="modal-buttons">
          <button class="modal-button cancel" @click="cancelDelete">取消</button>
          <button class="modal-button delete" @click="confirmDelete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { blogApi } from '@/api';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      items: [],
      showAddModal: false,
      newItem: {
        id: null,
        title: '',
        description: ''
      },
      itemToDelete: null, // 新增: 用于存储需要删除的item
      isAdmin: false, // 新增: 用于判断用户是否是管理员
      showDeleteModal: false
    };
  },
  methods: {
    handleItemClick(item, event) { // 修改: 添加事件参数
      if (event.button !== 2 && !this.itemToDelete) { // 修改: 只处理非右键点击且没有进行删除的情况
        this.itemToDelete = null;
        if (item.description) {
          window.open(item.description, '_blank');
        }
      }
    },
    handleRightClick(item) { // 新增: 处理右键点击的方法
      console.log('Right click detected'); // 添加日志
      if (this.isAdmin) { // 修改: 再检查是否为管理员
        console.log('User is admin'); // 添加日志
        if (this.itemToDelete === item) {
          this.itemToDelete = null; // 如果再次右键点击同一个item，隐藏删除按钮
        } else {
          this.itemToDelete = item;
        }
      } else {
        console.log('User is not admin'); // 添加日志
        this.itemToDelete = null; // 如果不是管理员，确保 itemToDelete 为 null
      }
    },
    goToHome() {
      this.$router.push({name: 'Blog'});
    },
    async fetchuuu() {
      try {
        const response = await axios.get(`/myhome/findAll`, {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
          }
        });
        console.log('响应数据:', response.data);
        if (Array.isArray(response.data)) {
          this.items = response.data;
        } else {
          console.error('无效的响应格式:', response.data);
        }
      } catch (error) {
        console.error('请求失败:', error.message);
        if (error.response) {
          console.error('状态码:', error.response.status);
          console.error('响应体:', error.response.data);
          if (error.response.status === 401) {
            localStorage.removeItem('jwtToken');
            this.$router.push('/');
          }
        }
      }
    },
    deleteNewItem() {
      // 删除逻辑可以根据实际需求实现
      console.log('删除按钮被点击');
    },
    addNewItem() {
      if (this.newItem.title && this.newItem.description) {
        axios.post('/myhome/add', this.newItem, {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
            'Content-Type': 'application/json'
          }
        })
          .then(response => {
            console.log('添加成功:', response.data);
            this.fetchuuu(); // 刷新数据列表
            this.showAddModal = false; // 关闭模态框
            this.newItem.title = ''; // 清空输入框
            this.newItem.description = '';
          })
          .catch(error => {
            console.error('添加失败:', error);
            if (error.response) {
              switch (error.response.status) {
                case 403:
                  ElMessage.error('没有权限执行此操作');
                  break;
                case 401:
                  ElMessage.error('登录已过期，请重新登录');
                  localStorage.removeItem('jwtToken');
                  this.$router.push('/');
                  break;
                default:
                  ElMessage.error(`添加失败: ${error.response.data.message || '未知错误'}`);
              }
            } else {
              ElMessage.error('网络错误，请稍后重试');
            }
          });
      } else {
        console.error('标题和描述不能为空');
      }
    },
    toggleDeleteButton(item) { // 修改: 切换删除按钮的显示状态
      if (this.itemToDelete === item) {
        this.itemToDelete = null;
      } else {
        this.itemToDelete = item;
      }
    },
    deleteItem(item) {
      axios.delete(`/myhome/delete/${item.id}`, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
      })
        .then(response => {
          console.log('删除成功:', response.data);
          this.fetchuuu(); // 刷新数据列表
          this.itemToDelete = null; // 关闭删除按钮
        })
        .catch(error => {
          console.error('删除失败:', error);
          if (error.response) {
            switch (error.response.status) {
              case 403:
                ElMessage.error('没有权限执行此操作');
                break;
              case 401:
                ElMessage.error('登录已过期，请重新登录');
                localStorage.removeItem('jwtToken');
                this.$router.push('/');
                break;
              default:
                ElMessage.error(`删除失败: ${error.response.data.message || '未知错误'}`);
            }
          } else {
            ElMessage.error('网络错误，请稍后重试');
          }
        });
    },
    showDeleteConfirm(item) {
      this.itemToDelete = item;
      this.showDeleteModal = true;
    },
    cancelDelete() {
      this.itemToDelete = null;
      this.showDeleteModal = false;
    },
    confirmDelete() {
      if (this.itemToDelete) {
        axios.delete(`/myhome/delete/${this.itemToDelete.id}`, {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
          }
        })
          .then(response => {
            console.log('删除成功:', response.data);
            this.fetchuuu(); // 刷新数据列表
            this.showDeleteModal = false;
            this.itemToDelete = null;
          })
          .catch(error => {
            console.error('删除失败:', error);
            if (error.response) {
              switch (error.response.status) {
                case 403:
                  ElMessage.error('没有权限执行此操作');
                  break;
                case 401:
                  ElMessage.error('登录已过期，请重新登录');
                  localStorage.removeItem('jwtToken');
                  this.$router.push('/');
                  break;
                default:
                  ElMessage.error(`删除失败: ${error.response.data.message || '未知错误'}`);
              }
            } else {
              ElMessage.error('网络错误，请稍后重试');
            }
          });
      }
    }
  },
  mounted() {
    this.fetchuuu();
    // 新增：获取用户权限
    axios.get('/api/user/role', {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      },
    })
    .then(response => {
      this.isAdmin = response.data.role === 'ROLE_ADMIN';
      console.log('User role:', response.data.role); // 添加日志
    })
    .catch(error => {
      // 添加：显示更详细的错误信息
      if (error.response && error.response.data) {
        console.error(`获取用户角色失败: ${error.response.data.message}`);
      } else {
        console.error('获取用户角色失败，请检查网络连接或重新登录');
      }
    });
  }
};
</script>

<style scoped>
.container {
  margin-top: 6px;
  position: relative;
  background-image: url('../assets/myhome.png');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: relative;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background-color: rgb(13, 28, 46);
  padding: 30px;
  border-radius: 15px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 0 20px rgba(3, 233, 244, 0.2);
  border: 1px solid rgba(3, 233, 244, 0.1);
  animation: modalFadeIn 0.3s ease;
}

.delete-confirm {
  max-width: 350px;
}

.modal-title {
  color: #03e9f4;
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  text-transform: uppercase;
  letter-spacing: 2px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 25px;
}

.modal-input {
  width: 100%;
  padding: 12px;
  border: 1px solid rgba(3, 233, 244, 0.3);
  background-color: rgba(3, 233, 244, 0.1);
  color: #03e9f4;
  border-radius: 5px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.modal-input:focus {
  outline: none;
  border-color: #03e9f4;
  box-shadow: 0 0 10px rgba(3, 233, 244, 0.2);
}

.modal-input::placeholder {
  color: rgba(3, 233, 244, 0.5);
}

.modal-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
}

.modal-button {
  padding: 10px 25px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.modal-button.cancel {
  background-color: transparent;
  border: 1px solid rgba(3, 233, 244, 0.3);
  color: #03e9f4;
}

.modal-button.confirm {
  background-color: #03e9f4;
  color: #0a1929;
}

.modal-button.delete {
  background-color: #ff3b3b;
  color: white;
}

.modal-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(3, 233, 244, 0.2);
}

.modal-button.cancel:hover {
  background-color: rgba(3, 233, 244, 0.1);
}

.modal-button.delete:hover {
  background-color: #ff1f1f;
  box-shadow: 0 5px 15px rgba(255, 59, 59, 0.2);
}

.delete-message {
  color: #fff;
  text-align: center;
  margin: 20px 0;
  font-size: 18px;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  padding: 20px;
}

.item {
  position: relative;
  margin: 0;
  width: 100%;
  height: 100px;
  text-align: center;
  text-transform: uppercase;
  text-decoration: none;
  font-size: 20px;
  letter-spacing: 3px;
  color: aqua;
  overflow: hidden;
  cursor: pointer;
  background-color: rgb(83 161 140 / 19%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-text {
  position: relative;
  z-index: 2;
  color: aqua;
  transition: color 0.3s ease;
}

.item:hover {
  background-color: aqua;
  box-shadow: 0 0 5px aqua, 0 0 75px aqua, 0 0 155px aqua;
}

.item:hover .item-text {
  color: black;
}

/* 边框动画效果 */
.border-line {
  position: absolute;
  display: block;
  z-index: 1;
}

/* 顶部边框 */
.border-line.top {
  top: 0;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #03e9f4);
  animation: btn-anim1 2.5s linear infinite;
}

/* 右侧边框 */
.border-line.right {
  top: -100%;
  right: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(180deg, transparent, #03e9f4);
  animation: btn-anim2 1s linear infinite;
  animation-delay: .5s;
}

/* 底部边框 */
.border-line.bottom {
  bottom: 0;
  right: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(270deg, transparent, #03e9f4);
  animation: btn-anim3 2s linear infinite;
  animation-delay: 1s;
}

/* 左侧边框 */
.border-line.left {
  bottom: -100%;
  left: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(360deg, transparent, #03e9f4);
  animation: btn-anim4 2s linear infinite;
  animation-delay: 1.5s;
}

@keyframes btn-anim1 {
  0% {
    left: -100%;
  }
  50%,100% {
    left: 100%;
  }
}

@keyframes btn-anim2 {
  0% {
    top: -100%;
  }
  50%,100% {
    top: 100%;
  }
}

@keyframes btn-anim3 {
  0% {
    right: -100%;
  }
  50%,100% {
    right: 100%;
  }
}

@keyframes btn-anim4 {
  0% {
    bottom: -100%;
  }
  50%,100% {
    bottom: 100%;
  }
}

.back-home-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 15px;
  z-index: 100;
}

.action-button {
  position: relative;
  width: 120px;
  height: 45px;
  background: rgba(4, 177, 255, 0.1);
  border: 1px solid rgba(4, 177, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

.action-button.add {
  background: rgba(3, 233, 244, 0.1);
  border: 1px solid rgba(3, 233, 244, 0.2);
}

.button-content {
  color: #04b1ff;
  font-size: 18px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 2px;
  z-index: 1;
  transition: all 0.3s ease;
}

.add .button-content {
  color: #03e9f4;
}

.button-glow {
  position: absolute;
  width: 20px;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(4, 177, 255, 0.3),
    transparent
  );
  animation: button-glow 2s linear infinite;
  transform: skewX(-45deg);
}

.add .button-glow {
  background: linear-gradient(
    90deg,
    transparent,
    rgba(3, 233, 244, 0.3),
    transparent
  );
}

.button-hover {
  position: absolute;
  inset: 0;
  background: transparent;
  transition: all 0.3s ease;
}

.action-button:hover {
  background: rgba(4, 177, 255, 0.2);
  border-color: #04b1ff;
  transform: translateY(-2px);
}

.action-button.add:hover {
  background: rgba(3, 233, 244, 0.2);
  border-color: #03e9f4;
}

.action-button:hover .button-content {
  color: white;
  text-shadow: 0 0 10px rgba(4, 177, 255, 0.5);
}

.action-button.add:hover .button-content {
  text-shadow: 0 0 10px rgba(3, 233, 244, 0.5);
}

.action-button:hover .button-hover {
  background: linear-gradient(
    45deg,
    transparent,
    rgba(4, 177, 255, 0.1),
    transparent
  );
}

.action-button.add:hover .button-hover {
  background: linear-gradient(
    45deg,
    transparent,
    rgba(3, 233, 244, 0.1),
    transparent
  );
}

@keyframes button-glow {
  0% {
    transform: translateX(-100%) skewX(-45deg);
  }
  100% {
    transform: translateX(200%) skewX(-45deg);
  }
}

.delete-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
  padding: 8px 15px;
  background-color: rgba(255, 59, 59, 0.2);
  color: #ff3b3b;
  font-size: 14px;
  border: 1px solid rgba(255, 59, 59, 0.3);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
  backdrop-filter: blur(4px);
  z-index: 3;
}

.delete-button:hover {
  background-color: #ff3b3b;
  color: white;
  box-shadow: 0 0 15px rgba(255, 59, 59, 0.3);
  transform: translateY(-2px);
}

.delete-button:active {
  transform: translateY(0);
  box-shadow: 0 0 5px rgba(255, 59, 59, 0.3);
}

/* 当鼠标悬停在item上时，让删除按钮更明显 */
.item:hover .delete-button {
  background-color: rgba(255, 59, 59, 0.3);
}

/* 确保删除按钮在item hover时保持可见 */
.item:hover .delete-button:hover {
  background-color: #ff3b3b;
}
</style>